<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属乡镇" prop="townShipId">
        <el-select v-model="queryParams.townShipId" clearable filterable placeholder="请选择所属乡镇">
          <el-option v-for="item in townList" :key="item.townShipId" :label="item.townShipName"
            :value="item.townShipId" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属分类" prop="classifyId">
        <el-select v-model="queryParams.classifyId" clearable filterable placeholder="请选择所属分类">
          <el-option v-for="item in shopTypeList" :key="item.classifyId" :label="item.classifyName"
            :value="item.classifyId" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架" prop="flag">
        <el-select v-model="queryParams.flag" clearable placeholder="请选择是否上架">
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['shop:goods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['shop:goods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['shop:goods:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['shop:goods:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-s-shop" size="mini" @click="handlePayment"
          v-hasPermi="['shop:goods:export']">是否开通商品支付</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 是否支付弹窗 -->
    <el-dialog title="是否开启商品支付功能" :visible.sync="dialogVisible" width="450px">
      <el-switch style="display: block" v-model="zfForm.flag" :active-value="1" :inactive-value="0"
        active-color="#13ce66" inactive-color="#ff4949" active-text="开启" inactive-text="关闭" @change="zfChange">
      </el-switch>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品id" align="center" prop="id" v-if="false" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品图片" align="center" prop="goodsImage">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.goodsImage" :key="index">
            <el-image fit="fit" :src="baseUrl + item" :preview-src-list="[baseUrl + item]"
              style="width:50px;height:50px;" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="所属乡镇" align="center" prop="townShipName" />
      <el-table-column label="所属分类" align="center" prop="classifyName" />
      <!-- <el-table-column label="详情" align="center" prop="introduce" /> -->
      <el-table-column label="价格(元)" align="center" prop="price" />
      <el-table-column label="库存量" align="center" prop="inventoryNum">
        <template slot-scope="scope">
          <el-link type="primary" @click="inventoryNumClick(scope.row)">{{ scope.row.inventoryNum }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="是否上架" align="center" prop="flag" width="180">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.flag" active-color="#13ce66" inactive-color="#ff4949" active-text="是"
            inactive-text="否" @change="flagTableChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:goods:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['shop:goods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品图片" prop="goodsImage">
          <ImageUpload v-model="form.goodsImage" @uploadImage="uploadImg" @remove="uploadImg" :limit="9" />
        </el-form-item>
        <el-form-item label="所属乡镇" prop="townShipId">
          <el-select v-model="form.townShipId" clearable filterable placeholder="请选择所属乡镇" @change="changeTownShipId">
            <el-option v-for="item in townList" :key="item.townShipId" :label="item.townShipName"
              :value="item.townShipId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属乡村" prop="villageId">
          <el-select v-model="form.villageId" clearable filterable placeholder="请选择所属乡镇" :disabled="!form.townShipId">
            <el-option v-for="item in this.listTownVillage" :key="item.villageId" :label="item.villageName"
              :value="item.villageId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属分类" prop="classifyId">
          <el-select v-model="form.classifyId" clearable filterable placeholder="请选择所属分类">
            <el-option v-for="item in shopTypeList" :key="item.classifyId" :label="item.classifyName"
              :value="item.classifyId" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存量" prop="inventoryNum">
          <el-input v-model="form.inventoryNum" placeholder="请输入库存量" />
        </el-form-item>
        <el-form-item label="价格（元）" prop="price">
          <el-input-number :min="0" v-model="form.price" placeholder="请输入价格（元）" />
        </el-form-item>
        <el-form-item label="详情" prop="introduce">
          <EDITOR v-if="open" v-model="form.introduce" :height="300" />
        </el-form-item>
        <el-form-item label="是否上架" prop="flag">
          <el-switch v-model="form.flag" active-color="#13ce66" inactive-color="#ff4949" active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listGoods,
    getGoods,
    delGoods,
    addGoods,
    updateGoods,
    exportGoods,
    listShopType,
    listTown,
    editPayFun,
    listPayFun,
    listTownVillage
  } from "@/api/shop/goods";
import { townNameList } from "@/api/route/travelRoute";
  import ImageUpload from "@/components/UploadImage";
  import EDITOR from "@/components/Editor";

  export default {
    name: "Goods",
    components: {
      ImageUpload,
      EDITOR
    },
    data() {
      return {
        //接口请求地址
        baseUrl: process.env.VUE_APP_BASE_API,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品管理表格数据
        goodsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          goodsName: null,
          goodsImage: null,
          townShipId: null,
          classifyId: null,
          introduce: null,
          inventoryNum: null,
          flag: null,
          price: null,
          imageScale: null,
          creatTime: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          goodsName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
          goodsImage: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
          townShipId: [{ required: true, message: '请选择所属乡镇', trigger: 'change' }],
          villageId: [{ required: true, message: '请选择所属乡村', trigger: 'change' }],
          classifyId: [{ required: true, message: '请选择所属分类', trigger: 'change' }],
          inventoryNum: [{ required: true, message: '请输入库存量', trigger: 'blur' }],
          flag: [{ required: true, message: '请选择是否上架', trigger: 'change' }],
          price: [{ required: true, message: '请输入价格（元）', trigger: 'blur' }],
        },
        //商品分类列表
        shopTypeList: [],
        //乡镇列表
        townList: [],
        // 某个乡镇下的村子
        listTownVillage:[],
        dialogVisible: false,
        //是否开启支付功能
        zfForm: {},
      };
    },
    created() {
      this.getList();
      this.getTownList();
      this.getShopTypeList();
    },
    methods: {
      // 乡镇选择改变
      async changeTownShipId(townShipId){
        // console.log('townShipId',e);
        let result = await listTownVillage({townShipId})
        // console.log('乡镇下的村子',result);
        this.listTownVillage = result.data
        console.log('乡镇下的村子',this.listTownVillage);

      },
      /** 查询商品管理列表 */
      getList() {
        this.loading = true;
        listGoods(this.queryParams).then(response => {
          this.goodsList = response.rows.map(item => ({
            ...item,
            goodsImage: item.goodsImage ? item.goodsImage.split(",") : []
          }));
          this.total = response.total;
          this.loading = false;
        });
      },
      //查询商品分类列表
      getShopTypeList() {
        listShopType().then(res => {
          this.shopTypeList = res.data;
        });
      },
      //查询乡镇列表
      getTownList() {
        listTown().then(res => {
          this.townList = res.data;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      //支付功能表单
      zfReset() {
        this.zfForm = {
          id: 1,
          flag: 0
        };
      },
      //获取支付功能状态
      getListPayFun() {
        listPayFun().then(res => {
          this.zfForm = res.data;
        });
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          goodsName: null,
          goodsImage: null,
          townShipId: null,
          classifyId: null,
          introduce: null,
          inventoryNum: null,
          flag: true,
          price: null,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      //table表单里库存数点击事件
      inventoryNumClick(row) {
        this.$prompt('请输入库存数量', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'number',
        }).then(({ value }) => {
          if (value) {
            updateGoods({ id: row.id, inventoryNum: value }).then(response => {
              this.msgSuccess(response.msg);
              this.getList();
            });
          } else {
            this.msgError('请输入库存数量')
          };

        }).catch(() => {
          this.msgInfo('已取消修改');
        });
      },
      //table表单里是否上架switch开关change事件
      flagTableChange(row) {
        let data = { ...row };
        data.goodsImage = data.goodsImage.length !== 0 ? data.goodsImage.toString() : "";
        this.$confirm("请确定是否修改商品名称为：" + data.goodsName + ",的是否上架的状态", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateGoods(data).then(response => {
            this.msgSuccess(response.msg);
            this.getList();
          });
        }).catch(err => {
          this.msgInfo('已取消修改');
          this.getList();
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加商品管理";
      },
      //商品图片上传图片组件回调函数
      uploadImg(e) {
        this.form.goodsImage = e;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        // console.log('点击修改',row.townShipId);
        this.changeTownShipId(row.townShipId)
        this.reset();
        const id = row.id || this.ids
        getGoods(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改商品管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateGoods(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addGoods(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除商品管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGoods(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有商品管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportGoods(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 是否开通支付按钮点击事件 */
      handlePayment() {
        this.zfReset();
        this.getListPayFun();
        this.dialogVisible = true;

      },
      /* 是否开启支付功能switch change事件 */
      zfChange(e) {
        editPayFun(this.zfForm).then(res => {
          console.log(res, 'res');
          this.msgSuccess(res.msg);
        });
      },
    }
  };
</script>